package org.example.helloworld.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.helloworld.entity.*;
import org.example.helloworld.service.IOrderInfoService;
import org.example.helloworld.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sy
 * @since 2024年07月09日
 */
@RestController
@RequestMapping("/orderInfo")
public class OrderInfoController {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private IUserService userService;
    @GetMapping("/selectallorder")
    public Result<Page<OrderInfo>> selectAllOrder(@RequestParam(defaultValue = "1") int current,
                                                  @RequestParam(defaultValue = "6") int size) {
        Page<OrderInfo> page = new Page<>(current, size); // 设置当前页码和每页记录数
        Page<OrderInfo> pageResult = orderInfoService.page(page, new QueryWrapper<OrderInfo>().orderByDesc("ord_id"));
        System.out.println(pageResult.getTotal());
        return Result.success(pageResult);
    }



    @GetMapping("/selectorderbyuserid")
    public Result<Page<OrderInfo>> selectOrderbyuserid(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "6") int size,
            @RequestParam(value = "user_id", required = false) String userId) {
        // 创建分页对象
        Page<OrderInfo> page = new Page<>(current, size);
        // 构建查询条件
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        if (userId != null && !userId.isEmpty()) {
            queryWrapper.eq("user_id", userId); // 添加用户ID的查询条件
        }
        queryWrapper.orderByDesc("ord_id"); // 按照订单ID降序排列
        // 执行分页查询
        Page<OrderInfo> pageResult = orderInfoService.page(page, queryWrapper);
        // 返回结果
        return Result.success(pageResult);
    }




    @GetMapping("/selectorderbyrealnameandifpay")
    public Result<Page<OrderInfo>> selectAllByrealnameandifpay(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "6") int size,
            @RequestParam(value = "realname", required = false) String realName,
            @RequestParam(value = "ifpay", required = false) String ifPay) {
        // 同上，创建分页对象和查询条件
        Page<OrderInfo> page = new Page<>(current, size);
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        if (realName != null && !realName.isEmpty()) {
//            queryWrapper.eq("realname", realName); // 添加真实姓名的查询条件
            queryWrapper.like("realname", realName);
        }
        if (ifPay != null && !ifPay.isEmpty()) {
//            queryWrapper.eq("ifpay", ifPay); // 添加支付状态的查询条件
        queryWrapper.like("ifpay", ifPay);
        }

        queryWrapper.orderByDesc("ord_id");
        Page<OrderInfo> pageResult = orderInfoService.page(page, queryWrapper);
        return Result.success(pageResult);
    }
    @GetMapping("/selectorderbyifpay")
    public Result<Page<OrderInfo>> selectAllByifpay(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "6") int size,
            @RequestParam(value = "user_id", required = false) String userId,
            @RequestParam(value = "ifpay", required = false) String ifPay) {
        // 创建分页对象
        Page<OrderInfo> page = new Page<>(current, size);
        // 构建查询条件
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        if (userId != null && !userId.isEmpty()) {
            queryWrapper.eq("User_id", userId); // 添加真实姓名的查询条件
        }
        if (ifPay != null && !ifPay.isEmpty()) {
            queryWrapper.eq("ifpay", ifPay); // 添加支付状态的查询条件
        }
        queryWrapper.orderByDesc("ord_id"); // 按照订单ID降序排列
        // 执行分页查询
        Page<OrderInfo> pageResult = orderInfoService.page(page, queryWrapper);
        // 返回结果
        return Result.success(pageResult);
    }





    @DeleteMapping("/{ord_id}")
    public boolean deleteorder(@PathVariable String ord_id) {
        return orderInfoService.removeById(ord_id);
    }


    @RequestMapping("/addorder") // 修改为 POST 请求，因为添加操作通常使用 POST
    public String addorder(@RequestBody OrderInfo orderInfo) {

        // 现在 orderInfo 对象已经包含了 JSON 请求体中的数据

        // 插入数据
        boolean result = orderInfoService.save(orderInfo);

        // 返回操作结果
        return result ? "success" : "failed";
    }


    @RequestMapping("/update")
    public Result pay(@RequestBody OrderInfo orderInfo) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ord_id", orderInfo.getOrdId());
        if (orderInfoService.getOne(queryWrapper) != null) {
            orderInfoService.updateById(orderInfo);
            return Result.success(orderInfo);
        } else {
            return Result.error("更新失败！");
        }
    }


    @GetMapping("/checkBalance")
    public Result<Boolean> checkBalance(@RequestParam(value = "ord_id") String orderId,
                                        @RequestParam(value = "user_id") String userId){
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        User user = userService.getById(userId);
        if (orderInfo == null) {
            return Result.error("订单不存在！");
        }

        // 假设 orderInfo 中的 sum 和 balance 都是 BigDecimal 类型
        BigDecimal sum = orderInfo.getSum(); // 订单总费用
        BigDecimal balance = user.getBalance(); // 用户余额

        // 使用 compareTo 方法比较 sum 是否小于等于 balance
        int result = sum.compareTo(balance);
        boolean enough = result <= 0; // 如果 result == 0 或 result < 0，则 enough 为 true
        System.out.println(enough);
        return Result.success(enough);
    }








    @RequestMapping("/updateorders")
    public Result updateorders(@RequestBody OrderInfo orderInfo) {

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ord_id", orderInfo.getOrdId());
        if (orderInfoService.getOne(queryWrapper) != null) {
            orderInfoService.updateById(orderInfo);
            return Result.success(orderInfo);
        } else {
            return Result.error("更新失败！");
        }
    }

}

